import {makeAutoObservable, runInAction} from "mobx";
import {TInitFlag} from "@/common/common";
import {apiGetUserInfo} from "@/common/apis/user";
import {clearUserInfo, getUserInfo, setUserInfo} from "@/common/util";
import avatar from '@/assets/images/avatar.svg'
import avatar2 from '@/assets/images/3.png'

interface UserInfo {
  user_name?: string
  nick_name?: string
  avatar?: string
  phone?: string
}

class UserInfoStore {
  constructor() {
    makeAutoObservable(this)
  }

  userInfo?: UserInfo
  initialFlg: TInitFlag = "initial";

  get NickName() {
    if (!this.userInfo) {
      return "-"
    }
    return this.userInfo.nick_name ? this.userInfo.nick_name : this.userInfo.user_name
  }

  get UserName() {
    if (!this.userInfo) {
      return "-"
    }
    return this.userInfo.user_name
  }

  get MobilePhone() {
    if (!this.userInfo) {
      return "-"
    }
    return this.userInfo.phone ? this.userInfo.phone : "暂未绑定手机号"
  }

  get Avatar() {
    if (!this.userInfo) {
      return avatar; // 未登录时的头像
    }
    // 已登录，但是未设过头像时
    return this.userInfo.avatar ? this.userInfo.avatar : avatar2
  }

  async reloadUserInfo() {
    this.initialFlg = "initial"
    clearUserInfo()
    await this.queryUserInfo()
  }

  async queryUserInfo() {
    const userInfo = getUserInfo()
    if (userInfo != null) {
      this.userInfo = userInfo
      return
    }
    if (this.initialFlg !== "initial") {
      return
    }
    this.initialFlg = "initialing";
    const res = await apiGetUserInfo()
    runInAction(() => {
      if (res.code === 0) {
        setUserInfo(res.data)
        this.userInfo = res.data
        this.initialFlg = "initialled"
      } else {
        this.initialFlg = "initial"
      }
    })
  }
}

export default new UserInfoStore()
